import type { App } from 'vue';

// import type { LocaleType } from '@mxpio/types';

import { $t, setupI18n as setupI18nLocales, registerI18nMessages } from '@mxpio/locales';

import { useStore } from '@mxpio/bridge';
import { setupI18n as setupI18nComponents } from '@mxpio/components';

// async function getMessages(locale: LocaleType) {
//   const modules = import.meta.glob('./lang/*.ts', { eager: true });
//   const defaultLocal: any = modules[`./lang/${locale}.ts`];
//   const message = defaultLocal.default?.message ?? {};
//   return message;
// }

export async function getMessages() {
  const modules = import.meta.glob('./lang/*.ts', { eager: true });
  const messages = Object.entries(modules).reduce(
    (acc, [path, mod]: [string, any]) => {
      const lang = path.split('/').pop()?.replace('.ts', '');
      if (lang) acc[lang] = mod.default?.message;
      return acc;
    },
    {} as Record<string, any>,
  );
  return messages;
}

async function setupI18n(app: App) {
  const useLocaleStoreWithOut = useStore('useLocaleStoreWithOut');
  const localeStore = useLocaleStoreWithOut();
  const locale = localeStore.getLocale;
  const messages = await getMessages();
  registerI18nMessages(messages);

  await setupI18nLocales(app, {
    locale: locale,
    messages: {
      // [locale]: await getMessages(locale),
      ...messages,
    },
  });
  // 注册组件库的国际化
  setupI18nComponents({ locale });
}

export { $t, setupI18n };
